﻿using System;
using System.Windows.Forms;

namespace Administracja
{
    public partial class InneObroty : Form
    {
        private int _id;

        public InneObroty()
        {
            InitializeComponent();
            typ.SelectedIndex = 0;
            try
            {
                lista.Items[0].Selected = true;
            }
            catch { }
        }

        private void Wyswietl()
        {
            string typS = typ.Text == "wszystkie" ? "%" : typ.Text;

            var reader2D = Baza.Wczytaj2D("SELECT * FROM INNE_OBROTY WHERE TYP LIKE '" + typS + "' ORDER BY DATA;");

            lista.Items.Clear();

            foreach (var reader1D in reader2D)
            {
                ListViewItem element = lista.Items.Add(reader1D[0]);
                element.SubItems.Add(reader1D[1].Substring(0, 10));
                element.SubItems.Add(Convert.ToDouble(reader1D[3].Replace('.', ',')).ToString("0.00"));
                element.SubItems.Add(reader1D[2]);
                element.SubItems.Add(reader1D[4]);
            }
        }

        private void DodajClick(object sender, EventArgs e)
        {
            int maxId = Baza.Ustaw("INNE_OBROTY");
            Baza.Zapisz("INSERT INTO INNE_OBROTY VALUES(GEN_ID(NUMERACJA_INNE_OBROTY,1),'" + DateTime.Now.ToString().Substring(0, 10) + "','','0','');");

            new InneObrotyEdycja(false, maxId).ShowDialog();

            Wyswietl();
        }

        private void EdytujClick(object sender, EventArgs e)
        {
            new InneObrotyEdycja(true, _id).ShowDialog();

            Wyswietl();
        }

        private void UsunClick(object sender, EventArgs e)
        {
            ListaSelectedIndexChanged(sender, e);

            if (DialogResult.Yes == Wyjatki.Komunikat("Czy na pewno chcesz usunąć rekord o ID = " + _id + "?", "Usunąć?", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
            {
                Baza.Zapisz("DELETE FROM INNE_OBROTY WHERE ID='" + _id + "';");

                Wyswietl();
            }
        }

        private void ZapiszClick(object sender, EventArgs e)
        {
            Close();
        }

        private void ObrotySelectedIndexChanged(object sender, EventArgs e)
        {
            Wyswietl();
        }

        private void ListaSelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                _id = Convert.ToInt32(lista.SelectedItems.Count > 0 ? lista.SelectedItems[0].Text : lista.Items[0].Text);
            }
            catch
            {
                _id = 1;
            }
        }

        private void DrukujClick(object sender, EventArgs e)
        {
            new InneObrotyDrukowanie(lista.Items.Count).ShowDialog();
        }
    }
}
